import {
  AppContainer,
  Divider,
  Form,
  Input,
  List,
  Modal,
  Progress,
  Spin,
  Tooltip,
  Utils,
} from "knowdesign";
import message from "@/components/Message";
import { IconFont } from "@knowdesign/icons";
import moment from "moment";
import React, {
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from "react";
import InfiniteScroll from "react-infinite-scroll-component";
import { Link, useHistory } from "react-router-dom";
import { IMetricPoint, linesMetric } from "./config";
import { useIntl } from "react-intl";
import api from "./api";
import { getDataUnit } from "@/constants/chartConfig";
import { SearchParams } from ".";

import SmallChart from "@/components/SmallChart";
import HealthState, { HealthStateEnum } from "@/components/HealthState";
import HttpUtils from "@/utils/HttpUtils";

const DEFAULT_PAGE_SIZE = 10;

export enum ClusterRunState {
  Raft = 2,
}

const DeleteCluster = React.forwardRef((_, ref) => {
  const intl = useIntl();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);
  const [clusterInfo, setClusterInfo] = useState<any>({});
  const callback = useRef(() => {
    return;
  });

  const onFinish = () => {
    // form.validateFields().then(() => {
    //   Utils.delete(api.phyCluster, {
    //     params: {
    //       clusterPhyId: clusterInfo.id,
    //     },
    //   }).then(() => {
    //     message.success("删除成功");
    //     callback.current();
    //     setVisible(false);
    //   });
    // });
  };

  useImperativeHandle(ref, () => ({
    onOpen: (clusterInfo: any, cbk: () => void) => {
      setClusterInfo(clusterInfo);
      callback.current = cbk;
      setVisible(true);
    },
  }));

  useEffect(() => {
    if (visible) {
      form.resetFields();
    }
  }, [visible]);

  return (
    <Modal
      width={570}
      destroyOnClose={true}
      centered={true}
      className="custom-modal"
      wrapClassName="del-topic-modal delete-modal"
      title={intl.formatMessage({
        id: "delete.cluster.confirm.title",
      })}
      visible={visible}
      onOk={onFinish}
      okText={intl.formatMessage({
        id: "btn.delete",
      })}
      cancelText={intl.formatMessage({
        id: "btn.cancel",
      })}
      onCancel={() => setVisible(false)}
      okButtonProps={{
        style: {
          width: 56,
        },
        danger: true,
        size: "small",
      }}
      cancelButtonProps={{
        style: {
          width: 56,
        },
        size: "small",
      }}
    >
      <div className="tip-info">
        <IconFont type="icon-warning-circle"></IconFont>
        <span>
          {intl.formatMessage({
            id: "delete.cluster.confirm.tip",
          })}
        </span>
      </div>
      <Form
        form={form}
        className="form"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        autoComplete="off"
      >
        <Form.Item label="集群名称" name="name">
          <span>{clusterInfo.name}</span>
        </Form.Item>
        <Form.Item
          label="集群名称"
          name="clusterName"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: "delete.cluster.confirm.cluster",
              }),
              validator: (rule: any, value: string) => {
                value = value || "";
                if (!value.trim() || value.trim() !== clusterInfo.name)
                  return Promise.reject(
                    intl.formatMessage({
                      id: "delete.cluster.confirm.cluster",
                    })
                  );
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
});

const ClusterList = (props: {
  searchParams: SearchParams;
  // showAccessCluster: any;
  // getPhyClusterState: any;
  // getExistKafkaVersion: any;
}) => {
  const {
    searchParams,
    // showAccessCluster,
    // getPhyClusterState,
    // getExistKafkaVersion,
  } = props;
  const [list, setList] = useState([]);
  const [clusterLoading, setClusterLoading] = useState<boolean>(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [pagination, setPagination] = useState({
    pageNo: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    total: 0,
  });
  const deleteModalRef = useRef(null);

  // 重置集群列表
  const reloadClusterList = (pageSize = DEFAULT_PAGE_SIZE) => {
    setClusterLoading(true);

    HttpUtils.post(api.executorPage, {
      page: pagination.pageNo,
      size: pagination.pageSize,
      searchKeywords: searchParams.keywords,
      sortField: "id",
      sortType: searchParams.sortInfo.sortType,
      statuses: searchParams.clusterStatus,
    })
      .then((res: any) => {
        if (res?.code === 200) {
          setList(res?.data?.bizData || []);
          setPagination(res?.data?.pagination);
        }
      })
      .finally(() => setClusterLoading(false));
  };

  // 重载列表
  useEffect(
    () =>
      searchParams.isReloadAll
        ? reloadClusterList(pagination.pageNo * pagination.pageSize)
        : reloadClusterList(),
    [searchParams]
  );

  function capitalizeFirstLetter(str: string) {
    if (!str) return str; // 如果字符串为空，直接返回
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  const RenderItem = (itemData: any) => {
    itemData = itemData || {};
    const metrics = linesMetric;
    // const metricPoints = [] as IMetricPoint[];

    const metricPoints = metrics.map((item) => {
      return {
        metricName: capitalizeFirstLetter(item),
        value: itemData[item] || 0,
        unit: "%",
      };
    });

    if (itemData?.registryValue) {
      metricPoints.push({
        metricName: "Registry Address",
        value: itemData["registryValue"],
        unit: "",
      });
    } else {
      metricPoints.push({
        metricName: "Registry Address",
        value: "-",
        unit: "",
      });
    }

    if (itemData?.pyPath) {
      metricPoints.push({
        metricName: "Python Path",
        value: itemData["pyPath"],
        unit: "",
      });
    } else {
      metricPoints.push({
        metricName: "Python Path",
        value: "-",
        unit: "",
      });
    }

    // const {
    //   HealthCheckPassed: healthCheckPassed,
    //   HealthCheckTotal: healthCheckTotal,
    // } = itemData.latestMetrics?.metrics || {};

    return (
      <List.Item
      // onClick={() => {
      //   history.push(`/cluster/${itemData.id}/cluster`);
      // }}
      >
        <div className="multi-cluster-list-item">
          <div className="multi-cluster-list-item-healthy">
            <div className="healthy-box">
              <HealthState
                state={
                  itemData?.status === 1
                    ? HealthStateEnum.GOOD
                    : HealthStateEnum.DOWN
                }
                width={70}
                height={70}
              />
              {/* <div className="healthy-degree">
                <span className="healthy-degree-status">通过</span>
                <span className="healthy-degree-proportion">
                  {healthCheckPassed}/{healthCheckTotal}
                </span>
              </div> */}
            </div>
          </div>
          <div className="multi-cluster-list-item-right">
            <div className="multi-cluster-list-item-base">
              <div className="multi-cluster-list-item-base-left">
                <div className="base-name">{itemData.appName ?? "-"}</div>
                <span className="base-version">{itemData.version ?? "-"}</span>

                <div
                  style={{
                    display: "flex",
                  }}
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                  }}
                >
                  {itemData?.status === 1 ? (
                    <div className="balance-box balanced">Executor 已均衡</div>
                  ) : (
                    <div className="balance-box unbalanced">
                      Executor 未均衡, 请启动执行器，后台自动注册
                    </div>
                  )}
                </div>
              </div>
              <div className="multi-cluster-list-item-base-date">
                {moment(itemData.createTime).format("YYYY-MM-DD HH:mm:ss")}
              </div>
            </div>
            <div className="multi-cluster-list-item-Indicator">
              <div className="indicator-left">
                <div className="indicator-left-item">
                  <div className="indicator-left-item-title">
                    <span
                      className="indicator-left-item-title-dot"
                      style={{
                        background:
                          itemData.status === 2 ? "#FF7066" : "#34C38F",
                      }}
                    ></span>
                    {itemData?.title}
                  </div>
                  {/* <div className="indicator-left-item-value">
                    {itemData?.title}
                  </div> */}
                </div>
              </div>
              <div className="indicator-right">
                {metricPoints.map((row, index) => {
                  return (
                    <Tooltip title={row?.value ?? row?.value}>
                      <div
                        key={row.metricName + index}
                        className={`indicator-right-item ${
                          row.metricName === "LeaderMessages"
                            ? "first-right-item"
                            : ""
                        }`}
                      >
                        <div className="indicator-right-item-total">
                          <div className="indicator-right-item-total-name">
                            {row.metricName === "TotalLogSize"
                              ? "-"
                              : row.metricName}
                          </div>
                          <div className="indicator-right-item-total-value">
                            {row.value}
                            <span className="total-value-unit">{row.unit}</span>
                          </div>
                        </div>
                        {/* <div className="indicator-right-item-chart">
                          <SmallChart
                            width={79}
                            height={40}
                            chartData={row.metricLines}
                          />
                        </div> */}
                      </div>
                    </Tooltip>
                  );
                })}
              </div>
            </div>
          </div>

          <div className="multi-cluster-list-item-btn">
            <div
              className="icon"
              onClick={(e) => {
                e.stopPropagation();
                // showAccessCluster(itemData);
              }}
            >
              <IconFont type="icon-duojiqunbianji" />
            </div>

            <div
              className="icon"
              onClick={(e) => {
                e.stopPropagation();
                // deleteModalRef.current.onOpen(itemData, () => {
                //   getPhyClusterState();
                //   getExistKafkaVersion(true);
                //   reloadClusterList(
                //     pagination.pageNo * pagination.pageSize
                //   );
                // });
              }}
            >
              <IconFont type="icon-duojiqunshanchu" />
            </div>
          </div>
        </div>
      </List.Item>
    );
  };

  return (
    <>
      <Spin spinning={clusterLoading}>
        <div style={{ height: "calc(100vh - 400px)", overflow: "auto" }}>
          {useMemo(
            () => (
              <InfiniteScroll
                dataLength={list.length}
                // next={loadMoreData}
                hasMore={list.length < pagination.total}
                loader={
                  <Spin
                    style={{ paddingLeft: "50%", paddingTop: 15 }}
                    spinning={true}
                  />
                }
                endMessage={
                  !pagination.total ? (
                    ""
                  ) : (
                    <Divider className="load-completed-tip" plain>
                      加载完成 共 {pagination.total} 条
                    </Divider>
                  )
                }
                scrollableTarget="scrollableDiv"
              >
                <List
                  bordered={false}
                  split={false}
                  className="multi-cluster-list"
                  itemLayout="horizontal"
                  dataSource={list}
                  renderItem={RenderItem}
                />
              </InfiniteScroll>
            ),
            [list, pagination, isLoadingMore]
          )}
        </div>

        <DeleteCluster ref={deleteModalRef} />
      </Spin>
    </>
  );
};
export default ClusterList;
